import logging
import time
# logging.basicConfig(
#     level=logging.INFO,
#     filename='/Users/lijia/PycharmProjects/user-insight/insight_agent/agent_langgraph_qiutingli/output/server.log',
#     filemode='w'
# )


from mcp.server import FastMCP

from group_profile.group_profile_process import GroupProfile
from group_profile.llm.analyst_agent import AnalystAgent
from group_profile.llm.analyst_agent_area import AnalystAgentArea
from group_profile.llm.analyst_agent_group import AnalystAgentGroup
from group_profile.llm.analyst_agent_stat import AnalystAgentStat
from group_profile.llm.purpose_agent import PurposeAgent

# 初始化 MCP 服务器
mcp = FastMCP("GroupProfileServer",
              # port=8181,
              # stateless_http=False,
              # json_response=False,
              # streamable_http_path="/mcp"
              server_options={"timeout": 86400}
              )
USER_AGENT = "group-profile-app/1.0"

# 初始化群组处理程序
group_profile_repo = GroupProfile()  # 群体数据准备
# group_profile.get_statics()
# group_profile.get_group(1)
purpose_agent = PurposeAgent()  # 意图识别智能体
analyst_agent = AnalystAgent()  # 基本对话智能体
analyst_agent_stat = AnalystAgentStat()  # 群组全局数据分析智能体
analyst_agent_area = AnalystAgentArea()  # 群组地区数据分析智能体
analyst_agent_group = AnalystAgentGroup()  # 群组具体数据分析智能体
history = []  # 对话记录

@mcp.tool()
async def group_profile(prompt):
    """
    洞察群体画像，包括群体全局数据、群体局部地区数据、群体具体数据（使用具体id查询）
    :param 查询群体的用户问题
    :return: 群体的数据解读
    """
    logging.info("正在识别用户意图")
    data = purpose_agent.purpose_chat(prompt, [])
    purpose = data['purpose']  # 用户意图code （0～3）
    reason = data['reason']  # 用户意图判断依据
    answer = ""
    if purpose == 0:
        logging.info("用户意图识别为:基础对话")
        logging.info(f"识别依据：{reason}")
        answer = analyst_agent.analyst_chat(None, prompt, history)
        # logging.info(answer)

    elif purpose == 1:
        logging.info("用户意图识别为:探索群体的全局情况")
        logging.info(f"识别依据：{reason}")
        # 查询群体全局信息
        logging.info("即将查询群体统计信息")
        group_info = group_profile_repo.get_statics()
        # logging.info(group_info)
        answer = analyst_agent_stat.analyst_chat(group_info, prompt, history)
        # logging.info(answer)

    elif purpose == 2:
        logging.info("用户意图识别为:探索群体的局部情况")
        logging.info(f"识别依据：{reason}")
        # 查询群体局部信息
        cities = data['value']
        # 查询群体个别信息
        logging.info("即将查询局部群体信息")
        city_groups = []
        for city in cities:
            city_groups += group_profile_repo.get_group_by_city(city)
        # logging.info(city_groups)

        answer = analyst_agent_area.analyst_chat(city_groups, prompt, history)
        # logging.info(answer)

    elif purpose == 3:
        logging.info("用户意图识别为:探索具体的群体")
        logging.info(f"识别依据：{reason}")
        groupids = data['value']
        # 查询群体个别信息
        logging.info("即将查询具体群体信息")
        groups = []
        for groupid in groupids:
            groups.append(group_profile_repo.get_group(groupid))
        # logging.info(groups)
        answer = analyst_agent_group.analyst_chat(groups, prompt, history)
        for groupid in groupids:
            group_profile_repo.draw_group(groupid)
        # logging.info(answer)

    else:
        logging.info("意图识别错误")

    history.append({
        "role": "user",
        "content": prompt
    })
    history.append({
        "role": "assistant",
        "content": answer
    })
    return answer


if __name__ == "__main__":
    # 以标准 I/O 方式运行 MCP 服务器
    mcp.run(transport='stdio')
